package org.szgb.console.wecom.robot.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WeComRobotService {
    private final HttpClient httpClient;

    @Value("${wecom.robot-api}")
    private String robotApi;

    @Autowired
    public WeComRobotService(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public void sendText(String text, String[] mentionedList) throws IOException, InterruptedException {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("msgtype", "text");
        Map<String, Object> textMap = new HashMap<>();
        textMap.put("content", text);
        textMap.put("mentioned_list", mentionedList);
        dataMap.put("text", textMap);
        // 使用 ObjectMapper 转为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody = null;
        try {
            jsonBody = objectMapper.writeValueAsString(dataMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // 处理异常
        }
        HttpRequest request = null;
        if (jsonBody != null) {
            request = HttpRequest.newBuilder()
                    .uri(URI.create(robotApi))
                    .timeout(Duration.ofSeconds(30))
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .build();
        }

        HttpResponse<String> response = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() != 200 && response.statusCode() != 201) {
            throw new RuntimeException("HTTP请求失败: " + response.statusCode());
        }
    }
}
